<template>
  <audio
    id="audio"
    :src="songInfo.playUrl"
    autoplay="autoplay"
    :ref="audio"
    preload="auto"
    @loadeddata="audioLoaded"
    @timeupdate="handleUpdateTime"
    @ended="handleEnd"
  ></audio>
  <audio :src="dingdong" id="noticePlayer"></audio>
</template>

<script>
import config from '@/service/config'
import { useStore } from 'vuex'
import { reactive, computed, nextTick, onMounted, onUnmounted, ref, toRefs, watch, watchEffect } from 'vue'
import CanvasBg from '../canvas'
import Lyric from 'lyric-parser'
export default {
  name: 'App',
  components: { CanvasBg },
  setup() {
    const store = useStore()
    const dingdong = require('../../assets/audio/dingdong.mp3')
    //获取歌词
    const handleLyric = ({ lineNum, txt }) => {
      // console.log(lineNum, txt)
      state.currentLineNum = lineNum
      store.commit('SET_STATE', {
        key: 'currentLineNum',
        value: lineNum
      })
      store.commit('SET_STATE', {
        key: 'playingLyric',
        value: txt
      })
      // if (lineNum > 1) {
      //   let lineEl = this.$refs.lyricLine[lineNum - 1]
      //   this.$refs.lyricList.scrollToElement(lineEl, 1000)
      // } else {
      //   this.$refs.lyricList.scrollTo(0, 0, 1000)
      // }
      state.playingLyric = txt
    }
    const state = reactive({
      currentLyric: null
    })
    let songId = computed(() => {
      return store.getters.songInfo.id
    })
    let lyric = computed(() => {
      return store.getters.lyric
    })
    watch(songId, async (nval, oval) => {
      console.log('nval = ' + nval + ', oval = ' + oval)
      if (nval == undefined) {
        state.currentLyric && state.currentLyric.stop()
        store.commit('SET_STATE', {
          key: 'currentLineNum',
          value: 0
        })
        state.currentLyric = null
        await store.commit('SET_STATE', {
          key: 'currentLyric',
          value: null
        })
        store.commit('SET_STATE', {
          key: 'playingLyric',
          value: ''
        })
        return
      }
      if (state.currentLyric) {
        state.currentLyric.stop()
        store.commit('SET_STATE', {
          key: 'currentLineNum',
          value: 0
        })
        state.currentLyric = null
        await store.commit('SET_STATE', {
          key: 'currentLyric',
          value: null
        })
        store.commit('SET_STATE', {
          key: 'playingLyric',
          value: ''
        })
      }
      nextTick(async () => {
        await store.dispatch('_getSongLyric')
        console.log(lyric)
        state.currentLyric = new Lyric(lyric.value, handleLyric)
        store.commit('SET_STATE', {
          key: 'currentLyric',
          value: state.currentLyric
        })
        let now = parseFloat((Date.now() - songInfo.value.since) / 1000).toFixed(2)
        if (isNaN(now)) {
          now = 0
        }
        console.log('获取歌词')
        state.currentLyric.seek(now * 1000)
      })
    })
    //监听音频
    let audioRef = ''
    const audio = el => {
      audioRef = el
    }
    const initPlay = async () => {
      let res = await store.dispatch('_getNowSong')
      console.log(res)
      if (res && res.data) {
        let item = {
          artist: res.data.artist,
          name: res.data.name,
          picUrl: res.data.picUrl,
          id: res.data.songId,
          since: res.data.since,
          duration: res.data.duration,
          nowDuration: res.data.nowDuration
        }
        store.commit('SET_STATE', { key: 'songInfo', value: item })
      }
    }
    const audioLoaded = () => {
      let now = parseFloat((Date.now() - songInfo.value.since) / 1000).toFixed(2)
      console.log('currentTime', audioRef.currentTime, now)
      if (isNaN(now)) {
        now = 0
      }
      nextTick(() => {
        audioRef.currentTime = now < 0 ? 0 : now
        if (songInfo.value.nowDuration == 0) {
          audioRef.currentTime = 0
        }
        state.currentLyric && state.currentLyric.seek(now * 1000)
        console.log('currentTime,加载完毕', audioRef.currentTime, now)
      })
    }
    let songInfo = computed(() => {
      return store.getters.songInfo
    })
    let currentTime = ref('')
    let duration = ref('')
    let songOrderList = computed(() => {
      return store.getters.songOrderList
    })
    const handleUpdateTime = e => {
      currentTime.value = e.target.currentTime
      duration.value = e.target.duration || 0
      let percent = (currentTime.value / duration.value) * 100
      percent = percent.toFixed(2)
      store.commit('SET_STATE', { key: 'percent', value: percent })
      store.commit('SET_STATE', { key: 'currentTime', value: currentTime.value })
      store.commit('SET_STATE', { key: 'duration', value: duration.value })
    }
    const handleEnd = () => {
      console.log('end')
      // store.dispatch('_postDelSongOrder')
    }

    onMounted(async () => {
      // initPlay()
      //获取用户信息
      await store.dispatch('_postUserDetail')
      store.dispatch('initSocket')
    })

    return { ...toRefs(state), dingdong, songInfo, handleUpdateTime, handleEnd, audio, audioLoaded }
  },
  computed: {
    volume() {
      return this.$store.getters.volume
    }
  },
  watch: {
    volume: {
      handler(v) {
        console.log(v)
        this.$nextTick(() => {
          let audio = document.getElementById('audio')
          if (audio) {
            audio.volume = parseFloat(v / 100)
          }
        })
      },
      immediate: true
    }
  },
  methods: {
    open() {
      this.$alert('即将播放音乐', {
        confirmButtonText: '确定',
        callback: action => {
          let audio = document.getElementById('audio')
          audio.play()
        }
      })
    }
  },
  mounted() {
    this.open()
  },
  beforeUnmount() {
    this.$store.dispatch('disconnect')
  }
}
</script>


